<template>
    <div>
        <index-header></index-header>
        <el-main class="main">

            <div class="detail-left">
                <div style="height:auto;text-align:left;">
                    <h4>相关推荐</h4>
                    <div style="height:auto;text-align:left;padding-top:1px;">
                        <ul class="left-ul">
                            <li v-for="item in relativeList" :key="item.bookId" @click="detail(item.bookId)">
                                <div style="width:42px;height: 53px;">
                                    <img style="width:42px;height:53px;" :src="item.bookpic" />
                                </div>
                                <div class="informa">
                            <li>《{{ item.bookname }}》</li>
                            <li>{{ item.author }}</li>
                            <!-- <li>{{ item.typename }}</li> -->
                            <li>{{ item.presshouse }}</li>
                    </div>
                    </li>
                    </ul>
                </div>

            </div>
    </div>
    <div class="detail-right">
        <div class="detail-img">
            <img style="width: 160px;height: 230px;" :src="bookDetail.bookpic" />
        </div>
        <div class="detail-text">
            <h4 id="bookName">《{{ bookDetail.bookname }}》</h4><br />
            <ul>
                <li id="bookId" style="display:none;">{{ bookDetail.bookId }}</li>
                <li>作者：{{ bookDetail.author }}</li>
                <li>出版社：{{ bookDetail.presshouse }}</li>
                <li>出版时间：{{ bookDetail.addtime }}</li>
                <li>价格：￥{{ bookDetail.price }}</li>
                <li>销量：{{ bookDetail.sales }}</li>
                <li>库存：{{ bookDetail.stock }}</li>
                <li>类别：{{ bookDetail.typename }}</li>
            </ul>

        </div>
        <div class="detail-discription">
            <h4>摘要:</h4>
            <p class="detail-discription-p">{{ bookDetail.discription }}</p>
        </div>
        <!-- 评价、计算数量、添加购物车、添加订单 -->
        <div class="countnum">
            <!-- <div class="countnum-1">
                <h4 style="font-size:16px;line-height:1px;">评分:</h4>
                <el-rate v-model="rate" allow-half style="height:0px;margin-top:20px;" />
            </div> -->
            <div class="countnum-1">
                <h4 style="font-size:16px;line-height:1px;">购买数量:</h4>
                <el-input-number style="margin-top:8px;margin-left:5px;" v-model="cart.cartNum" :min="1" :max="10"
                    size="small" />
            </div>
            <div class="countnum-3">

                <el-button type="success" icon="ShoppingCart" @click="addCart">添加购物车</el-button>
                <!-- <el-button type="primary" icon="Tickets" @click="addOrder">立即购买</el-button> -->
            </div>
        </div>
    </div>
    </el-main>

    <!-- 结算清单 -->
    <el-dialog v-model="centerDialogVisible" title="确认订单" width="50%" center>
        <div>
            <h4>已选商品:{{ cart.cartNum }}件</h4>
            <h4>总合计价格:<span id="total">{{ bookDetail.price * cart.cartNum }}</span>元</h4>
        </div>

        <el-table :data="payList" style="margin-bottom:30px;">
            <el-table-column property="bookname" label="商品名" width="250px" />
            <el-table-column property="price" label="价格/元" />
            <el-table-column property="" label="数量/本">{{ cart.cartNum }}</el-table-column>
            <el-table-column property="" label="小计/元">
                <template #default="scope">
                    {{ scope.row.price * cart.cartNum }}元
                </template>
            </el-table-column>
        </el-table>
        <div>
            <label>地址：</label>
            <el-select v-model="addressId" :data="addressList" placeholder="请选择收货地址" style="width:400px;">
                <el-option v-for="item in addressList" @click="AddresssubmitId(item.addressId)" :key="item.addressId"
                    :label="item.provinces + '/' + item.city + '/' + item.county + '/' + item.detailAddress"
                    :value="item.addressId">
                </el-option>
            </el-select>
            <br /> <br />
            <label>支付方式:</label>
            <el-select v-model="paytype" :data="payTypeList" placeholder="请选择支付方式" style="width:200px;">
                <el-option v-for="item in payTypeList" @click="setpayType(item.name)" :key="item.value"
                    :label="item.name" :value="item.name">
                </el-option>
            </el-select>

        </div>

        <template #footer>
            <span class="dialog-footer">
                <el-button @click="centerDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="submitPay">
                    提交
                </el-button>
            </span>
        </template>
    </el-dialog>
    </div>
</template>

<script>
import { reactive, toRefs, ref } from "vue";
import { bookDetailApi, changebookDetailApi, addCartApi, AddressApi, addgoodsApi } from "../utils/clientApi"
import { useRoute } from "vue-router"
import { useRouter } from "vue-router"
import indexHeader from './indexHeader.vue'
import { ElMessage } from 'element-plus'
export default {
    components: { indexHeader },
    name: "goodsDetail",
    setup(props) {
        const route = useRoute()
        const router = useRouter()
        const data = reactive({
            totalprice: 0,
            //总数量

            total: 0,
            payList: [],
            bookDetail: { addtime: "" },
            relativeList: [],
            time: '',
            cart: {
                u_Id: "",
                b_Id: "",
                cartNum: 1
            },
            centerDialogVisible: false,
            // 地址ID
            addressId: "",
            addressList: [],
            // 支付方式
            paytype: "",
            paytime: "",
            price: '',
            payTypeList: [{ "name": "微信", value: 1 }, { "name": "支付宝", value: 2 }]


        })

        const getBookDetail = (bookId) => {
            if (bookId > 0 && bookId != null) {
                bookDetailApi(bookId).then(res => {
                    if (res.status === 200) {
                        data.bookDetail = res.data.bookDetail
                        data.price = res.data.bookDetail.price
                        data.payList.push(data.bookDetail)
                        data.relativeList = res.data.pageInfo_relative.list
                        data.bookDetail.addtime = timeFormat(res.data.bookDetail.addtime)
                    } else {
                        ElMessage.error(res.msg)
                    }
                })
            }
        }
        getBookDetail(route.query.bookId)
        //   详情页
        const detail = (bookId) => {
            router.push({
                path: "/goodsdetail",
                query: { bookId: bookId }
            })
            changebookDetailApi(bookId).then(res => {
                if (res.status === 200) {
                    data.bookDetail = res.data.bookDetail
                    data.bookDetail.addtime = timeFormat(res.data.bookDetail.addtime)
                    data.relativeList = res.data.pageInfo_relative.list
                } else {
                    ElMessage.error(res.msg)
                }
            })
        }


        //时间格式化（需要注意date为空）
        const timeFormat = (date) => {
            if (date) {
                let newDate = /\d{4}-\d{1,2}-\d{1,2}/g.exec(date)
                return newDate[0]
            } else {
                return ''
            }
        }


        //      添加购物车
        const addCart = () => {
            if (localStorage.getItem("token")) {
                // 获取bookId
                data.cart.b_Id = document.getElementById("bookId").innerHTML;
                // 获取用户id
                data.cart.u_Id = JSON.parse(localStorage.getItem("userInfo")).id
                try {
                    addCartApi(JSON.stringify(data.cart)).then(res => {
                        if (res.status === 200) {
                            ElMessage.success(res.msg)
                        } else if (res.status === 201) {
                            getBookDetail(route.query.bookId)
                        } else if (res.status === 202) {
                            getBookDetail(route.query.bookId)
                        }
                    })
                } catch (error) {
                    ElMessage.error(error)

                }
            } else {
                ElMessage.error("当前未登录！")
            }

        }
        // 确认订单
        const addOrder = () => {
            if (localStorage.getItem("token")) {
                data.centerDialogVisible = true
                // 获取bookId
                data.cart.b_Id = document.getElementById("bookId").innerHTML;
                // 商品数量
                // data.cart.cartNum = document.getElementById("cartNum").innerHTML;
                // 获取用户id
                data.cart.u_Id = JSON.parse(localStorage.getItem("userInfo")).id
                getAddressList()
                // ElMessage.success("success")        // 获取用户地址列表

            } else {
                ElMessage.error("当前未登录！")
            }

        }
        // 获取地址
        const getAddressList = () => {
            const id = JSON.parse(localStorage.getItem("userInfo")).id
            AddressApi(id).then(res => {
                data.addressList = res.data
                data.addressList.forEach((item) => {
                    if (item.isDefault == 1) {
                        // 赋值默认地址
                        data.addressId = item.addressId

                    }
                })
            })
        }
        // 选择支付方式
        const setpayType = (value) => {
            data.paytype = value
            data.paytime = Date.parse(new Date());
            // if(value === '支付')
        }
        const AddresssubmitId = (id) => {
            // 修改地址id
            data.addressId = id
            // console.log("我是修改后的地址ID",data.addressId);
        }

        // 处理map转json为空
        const strMapToObj = (strMap) => {
            let obj = Object.create(null);
            for (let [k, v] of strMap) {
                obj[k] = v;
            }
            return obj;
        }
        // 提交
        const submitPay = () => {
            // 提交的内容
            if (data.paytype.length !== 0) {

                let map = new Map();
                const totalprice = document.getElementById("total").innerHTML
                data.cart.b_Id = document.getElementById("bookId").innerHTML;
                map.set("addressId", data.addressId)
                map.set("goodId", data.cart.b_Id)
                map.set("paytype", data.paytype)
                map.set("price", data.price)
                map.set("uid", data.cart.u_Id)
                map.set("countNum", data.cart.cartNum)
                map.set("amountMoney", totalprice)
                map.set("paytime", data.paytime)
                const subject = document.getElementById("bookName").innerHTML
                const uname = JSON.parse(localStorage.getItem("userInfo")).name
                addgoodsApi(JSON.stringify(strMapToObj(map))).then(res => {
                    if (res.status === 200) {
                        ElMessage.success(res.msg)
                        data.centerDialogVisible = false
                        router.push({
                            path: '/order'
                        })
                    } else if (res.status === 201) {
                        ElMessage.error(res.msg)
                    }
                })

            } else {
                ElMessage.error("请选择支付方式")
            }
        }




        const num = ref(1)
        const rate = ref()
        // const handleChange = (number) => {
        //     console.log(number)
        // }


        return {
            ...toRefs(data), detail, num, rate, timeFormat, addCart,
            addOrder, submitPay, getAddressList, setpayType, AddresssubmitId

        }
    }
}
</script>

<style scope>
.main {
    width: 1200px;
    height: auto;
    overflow: hidden;
    margin: 0 auto;

}

/*相关推荐
*/
.detail-left {
    width: 250px;
    height: auto;
    float: left;
    margin-right: 20px;
}

.left-ul {
    margin-top: 45px;
    padding-left: 20px;
}

.left-ul>li {
    display: block;
    width: 240px;
    height: 60px;
    font-size: 10px;
    color: #868989;
    text-align: left;
    margin-bottom: 7px;
    margin-left: 0px;

}

.left-ul>li:hover {

    cursor: pointer;
    background: #EAEAED;
}

.informa {
    width: 170px;
    height: 50px;
    position: relative;
    top: -53px;
    left: 60px;
    font-size: 10px;
}

.informa>li {
    display: block;
    margin-top: 3px;
}





/*详情
*/
.detail-right {
    width: 889px;
    height: auto;
    background: #EAEAED;
    float: left;
}

.detail-img {
    width: 160px;
    height: 230px;
    margin: 15px 12px 10px 12px;
    float: left;
}

.detail-text {
    width: 680px;
    height: auto;
    margin: 15px 12px 10px 12px;
    float: left;
}

h4 {
    display: block;
    float: left;
    padding-left: 12px;
    line-height: 3px;


}

.detail-text>ul {
    margin-top: 45px;
    padding-left: 20px;
}

.detail-text>ul>li {
    display: block;
    width: 300px;
    height: auto;
    font-size: 14px;
    color: #868989;
    text-align: left;
    margin-bottom: 7px;
    margin-left: 0px;

}

.detail-discription {
    width: 870px;
    height: auto;
    position: relative;
    left: 12px;
    float: left;
}

.detail-discription-p {
    display: block;
    width: 854px;
    height: auto;
    margin-top: 46px;
    margin-left: 12px;
    text-align: left;
    text-indent: 2em;
}

/*添加*/
.countnum {
    width: 889px;
    height: 200px;
    float: left;

}

.countnum-1 {
    width: 877px;
    margin-top: 10px;
    text-align: left;
    padding-left: 12px;
    height: 34px;

}


.countnum-3 {
    margin-top: 70px;
    text-align: right;
    height: 34px;
    padding-right: 20px;
}
</style>